const { readFileSync }  = require('fs')
const { resolve } = require('path')
const INNER_MARK = '<!-- inner -->'
const compileHtTML = require('./compileHTML')
const { RawSource } = require('webpack-sources');

class MyMdToHtmlPlugin {
    constructor({ template, filename }) {
        if (!template) throw new Error('The config "template" must be configured!')
        this.template = template
        this.filename = filename ? filename : 'md.html'
    }
    apply(compiler) {
        // compiler：Webpack 的核心对象，代表整个构建生命周期
        compiler.hooks.thisCompilation.tap('MyMdToHtmlPlugin', (compilation) => {
            compilation.hooks.processAssets.tap(
                {
                    name: 'MyMdToHtmlPlugin',
                    stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
                },
                () => {
                    const _mdContent = readFileSync(this.template, 'utf-8')
                    const _templateHTML = readFileSync(resolve(__dirname, 'template.html'), 'utf-8')
                    const _contentArray = _mdContent.split('\n')
                    const _htmlStr = compileHtTML(_contentArray)
                    const _finallyHTML = _templateHTML.replace(INNER_MARK, _htmlStr)

                    // 使用现代API添加资源
                    compilation.emitAsset(
                        this.filename,
                        new RawSource(_finallyHTML),
                        {
                            size: Buffer.byteLength(_finallyHTML, 'utf8')
                        }
                    )
                }
            )
        })
    }
}

module.exports = MyMdToHtmlPlugin 